import { Directive, DirectiveBinding } from 'vue'

/** 拖拽指令 */
export const directive: Directive<HTMLElement, any> = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    el.style.cursor = 'move'
    const onMousedown = (e: MouseEvent) => {
      console.log('onMousedown')
      el.innerHTML = binding.value

      // 记录鼠标按下时，在该元素内的坐标
      const X = e.clientX - el.offsetLeft
      const Y = e.clientY - el.offsetTop
      const onMousemove = (e: MouseEvent) => {
        el.style.position = 'fixed'
        el.style.left = e.clientX - X + 'px'
        el.style.top = e.clientY - Y + 'px'
      }
      document.addEventListener('mousemove', onMousemove)
      document.addEventListener('mouseup', () => {
        document.removeEventListener('mousemove', onMousemove)
        // el.style.position = ''
        el.innerHTML = ''
      })
    }

    el.addEventListener('mousedown', onMousedown)
  },
  unmounted() {
    // el.removeEventListener('mousedown', onMousedown)
  }
}
export default directive
